import React from "react";
import { useState } from "react";
import { useSelector } from "react-redux";
import { lazyRoutes } from '@/router/routes'
import { lazyLoad, load, redirect, setRouteBefore } from './utilsFn/fn'
import Login from '@/pages/login'
import NotFound from '@/components/notFound'
import { useRoutes, Navigate, RouteObject } from 'react-router-dom';

function handleRouter(routes){
  let app = routes.map((item) => {
		const Element = lazyRoutes[item.key];
		const path = item.path.replace(/\/(.*)\/|\//g, '');
		if (Array.isArray(item.children) && item.children.length) {
			if (Element) {
				return {
					path,
					element: Element,
					children: handleRouter(item.children)
				};
			} else {
				const firstPath = item.children[0].path;
				return {
					path,
					children: [
						{
							index: true,
							element: (
								<Navigate to={firstPath} replace />
							)
						},
						...handleRouter(item.children)
					]
				};
			}
		} else if (Element) {
			return { path, element: Element};
		} else {
			return {
				path,
				element: <NotFound />
			};
		}
	});
  return app
}

export default function AppRouter() {
  const { routes } = useSelector(state => state)
  const allRoutes = [
    {
      path: '/',
      element: redirect('/home')
    }, {
      path: '/home',
      element: lazyLoad(() => import('@/pages/home'), { title: '首页', needLogin: true }),// 懒加载
      children: [
        // {
        //   path: 'option1',
        //   element: lazyLoad(() => import('../pages/option/options1'), { title: 'options11', needLogin: true }),// 懒加载
        // },
        ...handleRouter(routes)
      ]
    }, {
      path: '/login',
      element: load(<Login />, { title: '登录', needLogin: false })// 普通加载
    },
    {
      path: '*',
      element: lazyLoad(() => import('@/components/notFound'), { title: '页面丢失', needLogin: true })
    }
  ]
  console.log(allRoutes);
  return useRoutes(allRoutes)
}


